// pages/weijieke/product/index.js
const app = getApp();
const utils = require('../../../utils/util.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    seltoid: '',//商家uid
    pid: 0, //商品PID
    title: '', //商品名
    state: 0, //0代表上架，1代表下架
    cateid: 195, //195其他分类(单品), 375 优惠券商品, 376 套餐商品
    bprice: '', //商品价格
    yjprice: 0, //佣金价格
    costPrice: 0, //成本价
    sort: '', //排序
    videoSrc: "", //视频
    selType: 0,//购买限制;0无限制，1限购一份，2每天限购一份
    date: '', // 有效期
    cutPoicy: '', //优惠政策
    count: '', //数量
    StoreCid: 0,  //分类id
    classList: [],
    indexk: 0,
    description: '',
    detailPics: [], //商品头图集合
    productPic: [], //详情图
    showDetailPics: [], //渲染商品头图集合
    showproductPic: [], //渲染详情图集合
    showDialogSku: false,
    skulist: [], //所有规格,
    skulistChoose: [], //新增产品时选择的规格
    top: 70,
    showLive: false,
    clickLive: 0,
    liveList: [],
    lastLiveList: [],  
    navTitle: '产品',    //导航标题
    industryCode: 0
  },

//购买限制
  bindBuyType: function(e) {
    this.setData({
      selType: e.currentTarget.dataset.seltype
    })
  },

  chooseLive: function(){
    let clickLive = this.data.clickLive;
    this.setData({
      showLive: true
    })
    if(clickLive == 0){
      this.getLiveList();
      this.data.clickLive += 1;
    }
  },
  closeLive:  function(){
    this.setData({
      showLive: false
    })
  },
  selectLive: function(e){
    let id = e.currentTarget.dataset.id;    
    let liveList = this.data.liveList;
    for(let i = 0; i < liveList.length; i++){
      if(liveList[i].Id == id){     
        liveList[i].isSelect = liveList[i].isSelect == 1 ? 0 : 1
        break;
      }
    }
    let selList = [];
    for(let j = 0; j < liveList.length; j++){
      if(liveList[j].isSelect == 1){
        selList.push(liveList[j]);
      }
    }
    this.setData({
      liveList: liveList,
      lastLiveList: selList
    })
  },

  // 直播列表
  getLiveList: function () {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/weapp/GetLiveListByUser?uid=' + app.globalData.userInfo.Uid + '&storeId=' + app.globalData.storeId,
      success: function (res) {
        if(res.data.Code == 0){
          let liveList = res.data.Data.Items;
          let showList = [];
          if (liveList && liveList.length > 0) {
            //101 直播中102 未开始103 已结束104 禁播105 暂停中106 异常107 已过期
            for (let i = 0; i < liveList.length; i++) {
              liveList[i].CoverImg = utils.formatAvater(liveList[i].CoverImg, 'https://static.711688.net.cn/upload/adv/');
              liveList[i].ShareImg = utils.formatAvater(liveList[i].ShareImg, 'https://static.711688.net.cn/upload/adv/');
              liveList[i].isSelect = 0;
              if(liveList[i].CheckStatus == 1){
                var status = '已过期';
                switch(liveList[i].LiveStatus){
                  case 101: status = '直播中'; break;
                  case 102: status = '未开始'; break;
                  case 103: status = '已结束'; break;
                  case 104: status = '禁播'; break;
                  case 105: status = '暂停中'; break;
                  case 106: status = '异常'; break;
                }
                if(status != '已过期'){
                  liveList[i].status = status;
                  showList.push(liveList[i]);
                }               
              }
            }            
          }
          let lastLiveList = that.data.lastLiveList;
          for(let i = 0; i < lastLiveList.length; i++){
            for(let j = 0; j < showList.length; j++){
              if(showList[j].Id == lastLiveList[i].Id){
                showList[j].isSelect = 1;
                showList[i].CoverImg = utils.formatAvater(showList[i].CoverImg, 'https://static.711688.net.cn/upload/adv/');
                showList[i].ShareImg = utils.formatAvater(showList[i].ShareImg, 'https://static.711688.net.cn/upload/adv/');
              }
            }
          }
          that.setData({
            liveList: showList
          })
        }
      },
    })
  },

  /**
   * 长按删除详细图片
   */
  deleteDetailPic: function(e) {
    var that = this;
    var pic = e.currentTarget.dataset.pic;
    if (pic == 1) {
      var newPics = that.data.detailPics;
      let showDetailPics = that.data.showDetailPics;
      newPics.splice(e.currentTarget.dataset.index, 1);
      showDetailPics.splice(e.currentTarget.dataset.index, 1);
      that.setData({
        detailPics: newPics,
        showDetailPics: showDetailPics
      })
    } else {
      var newPics = that.data.productPic;
      let showProductPic = that.data.showProductPic;
      newPics.splice(e.currentTarget.dataset.index, 1);
      showProductPic.splice(e.currentTarget.dataset.index, 1);

      that.setData({
        productPic: newPics,
        showProductPic: showProductPic
      })
    }
  },
  /**
   * 上传详细图片
   */
  uploadDetailImage: function(e) { //这里是选取图片的方法
    var that = this;
    var detailPics = [];
    var pic = e.currentTarget.dataset.pic;
    that.setData({
      picIndex: pic
    })
    if (pic == 1) { //头图
      detailPics = that.data.detailPics
    } else { //详情图片
      detailPics = that.data.productPic;
    }
    var pics = [];
    if (detailPics.length >= 6) {
      utils.showToast('最多选择6张！'); return;
    }
    wx.chooseImage({
      count: 6, // 最多可以选择的图片张数，默认9
      sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      success: function(res) {
        var imgs = res.tempFilePaths;
        for (var i = 0; i < imgs.length; i++) {
          if (pics.length < 6 - detailPics.length) {
            pics.push(imgs[i]);
          }
        }
        let url = app.globalData.host + '/api/tool/upload?operation=uploadproductimage&storeid=' + app.globalData.storeId;
        if(pic != 1){//详情图上传接口
          url = app.globalData.host + '/api/tool/upload?operation=saveproducteditorimage&storeid=' + app.globalData.storeId;
        }
        that.uploadimg({
          url: url, //这里是你图片上传的接口
          path: pics, //这里是选取的图片的地址数组
        });
      },
    })
  },


  //多张图片上传
  uploadimg: function(data) {
    wx.showLoading({title: '提交中...',mask: true,})
    var that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    wx.uploadFile({
      url: data.url,
      filePath: data.path[i],
      name: 'fileData',
      formData: null,
      success: (resp) => {
        wx.hideLoading();
        success++;
        var str = resp.data
        var pic = JSON.parse(str);
        var pic_name = pic.Data;
        if (that.data.picIndex == 1) {//头图
          var detailPics = that.data.detailPics;
          detailPics.push(pic_name);
          var showDetailPics = detailPics.concat();
          for(let i = 0; i < showDetailPics.length; i++){
            if(showDetailPics[i].indexOf('ps') != -1){
              showDetailPics[i] = utils.formatAvaterByProHead(showDetailPics[i]);
            }else{
              showDetailPics[i] = utils.formatAvater(showDetailPics[i], 'https://static.711688.net.cn/upload/store/' + app.globalData.storeId + '/product/editor/');
            }
          }
          that.setData({
            detailPics: detailPics,
            showDetailPics: showDetailPics
          })
        } else {
          var productPic = that.data.productPic;
          productPic.push(pic_name);

          var showProductPic = productPic.concat();
          for(let j = 0; j < showProductPic.length; j++){
            showProductPic[j] = utils.formatAvater(showProductPic[j], 'https://static.711688.net.cn/upload/store/' + app.globalData.storeId + '/product/editor/');
          }
          that.setData({
            productPic: productPic,
            showProductPic: showProductPic
          })
        }
      },
      fail: (res) => {
        fail++;
        console.log('fail:' + i + "fail:" + fail);
      },
      complete: () => {
        i++;
        if (i == data.path.length) { //当图片传完时，停止调用     
          console.log('成功：' + success + " 失败：" + fail);
        } else { //若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadimg(data);
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if (options.backpage) {
      this.setData({
        backpage: options.backpage
      })
    }
    if (options.seltoid) {
      let pid = options.pid ? options.pid : 0
      this.getGoodsClassList(pid,options.seltoid);
      this.setData({
        seltoid: options.seltoid
      })
    }
    if (options.pid) {      
      this.getGoodsSku(options.pid);
      this.setData({
        pid: options.pid
      })
    }
    if(options.industryCode){
      this.setData({
        industryCode: options.industryCode
      })
    }
  },

  onShow: function() {
    this.getSkuList();
  },

  deleteProduct: function() {
    var that = this;
    let pid = that.data.pid;
    wx.showModal({
      title: '提示',
      content: '确认是否删除！',
      success(res) {
        if (res.confirm) {
          wx.showLoading({
            title: '正在删除',
            mask: true,
          })
          wx.request({
            url: app.globalData.host + "/api/Store/RecycleProductById?pids=" + pid,
            success: function(res) {
              wx.hideLoading();
              if (res.data.Code == 0) {
                wx.navigateTo({
                  url: '/pages/classes-new/index',
                })
              } else {
                utils.showModal(res.data.Message);
              }
            }
          })
        } 
      }
    })
  },

  skuManage: function() {
    wx.navigateTo({
      url: '/order/order/skuManage/index',
    })
  },
  getSkuList: function() {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Product/GetOptionList?uid=' + app.globalData.userInfo.Uid + '&tagId=0',
      success: function(res) {
        if (res.data.Code == 0) {
          let list = res.data.Data;
          for (let i = 0; i < list.length; i++) {
            list[i].select = 0;
          }      
          that.setData({
            skulist: list
          })
        } else {
          utils.showModal(res.data.Message);          
        }
      }
    })
  },

  //获取商品详情
  getGoodDetails: function(pid) {
    var that = this;
    var classList = that.data.classList;
    if (pid <= 0) return;
    wx.request({
      url: app.globalData.host + '/api/store/Product?pid=' + pid + '&isextend=1&isLive=1',
      success: function(res) {
        if(res.data.Code == 0){
          let selType = 0;
          let extend = res.data.Data.Extend;
          let product = res.data.Data.ProductInfo;
          let productPic = product.DetailPics ? JSON.parse(product.DetailPics) : [];
          let showProductPic = [];            
          let detailPics = [];
          let showDetailPics = [];
          let picPath= 'https://static.711688.net.cn/upload/store/' + app.globalData.storeId + '/product/editor/';
          if(res.data.Data.SinglePromotionInfo){
            selType = 1;    //限购一份
            if(res.data.Data.SinglePromotionInfo.DayBuyCount>0){
              selType = 2;  //每天限购一份
            }
          }
          //标签
          for (let i = 0; i < classList.length; i++) {
            if (classList[i].StoreCid == product.StoreCid) {
              that.setData({indexk: i})
            }
          }
          //详情图            
          for(let i = 0; i < productPic.length; i++){
            showProductPic[i] = utils.formatAvater(productPic[i], picPath);
          } 
          //头图            
          for(let i = 0; i < res.data.Data.ProductImageList.length; i++){
            let image =res.data.Data.ProductImageList[i];
            detailPics.push(image.ShowImg);
            showDetailPics.push(
              image.ShowImg.indexOf('ps') != -1 ?
              utils.formatAvaterByProHead(image.ShowImg) : 
              utils.formatAvater(image.ShowImg, picPath));
          }
          
          let expiretime = '';
          if(extend && extend.UseEndTime.indexOf('1970') == -1){
            expiretime = extend.UseEndTime.substr(0,10);
          }
          //直播
          let liveList = [];
          if(res.data.Data.LiveList.length > 0){
            liveList = res.data.Data.LiveList;
            for(let i = 0; i < liveList.length; i++){
              liveList[i].isSelect = 1;
              liveList[i].CoverImg = utils.formatAvater(liveList[i].CoverImg, 'https://static.711688.net.cn/upload/adv/');
              liveList[i].ShareImg = utils.formatAvater(liveList[i].ShareImg, 'https://static.711688.net.cn/upload/adv/');
              liveList[i].status = '已过期';
              switch(liveList[i].LiveStatus){
                case 101: liveList[i].status = '直播中'; break;
                case 102: liveList[i].status = '未开始'; break;
                case 103: liveList[i].status = '已结束'; break;
                case 104: liveList[i].status = '禁播'; break;
                case 105: liveList[i].status = '暂停中'; break;
                case 106: liveList[i].status = '异常'; break;
              }                       
            }
          }

          that.setData({
            pid: pid,
            cateid: product.CateId,
            title: product.Name,
            bprice: product.ShopPrice,
            costPrice: product.CostPrice,
            yjprice: extend.BrokeragePrice,
            description: product.Description,
            detailPics: detailPics,
            showDetailPics: showDetailPics,
            sort: product.DisplayOrder,
            videoSrc: product.VideoSrc,
            cutPoicy: product.ShadowPrice,
            StoreCid: product.StoreCid,
            state: product.State,
            productPic: productPic ? productPic : [],
            showProductPic: showProductPic,
            count: res.data.Data.StockNumber,
            date: expiretime,
            selType:selType,
            lastLiveList: liveList,
            salecount: product.SaleCount,
            regionList: extend.Regions== '' ? [] : extend.Regions.split(','),  //指定区域
            navTitle: product.CateId == 377 || product.CateId==378 ? '项目': '产品'
          })
        
        }        
      }
    })    
  },
  getGoodsSku: function(pid) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/product/GetProductOptionListByPid?pid=' + pid,
      success: function(res) {
        if (res.data.Code == 0) {
          let list = res.data.Data;
          let skulist = that.data.skulist;
          if (list.length > 0) {
            for (let i = 0; i < list.length; i++) {
              list[i].select = 1;
              for (let j = 0; j < skulist.length; j++) {
                if (skulist[j].TagId == list[i].TagId) {
                  skulist[j].select = 1;
                }
              }
            }
            that.setData({
              skulistChoose: list,
              skulist: skulist
            })
          }
        } else {
          utils.showModal(res.data.Message); 
        }
      }
    })
  },

  // 新增产品
  saveProduct: function() {
    let that = this;
    let optionids = '';
    let liveIds = '';
    for (let i = 0; i < that.data.skulistChoose.length; i++) {
      let options = that.data.skulistChoose[i].OptionList;
      for (let j = 0; j < options.length; j++) {
        optionids += optionids.length>0 ? ',' : '';
        optionids += options[j].OptionId + ',';
      }
    }
    for(let i = 0; i < that.data.liveList.length; i++){
      let liveList = that.data.liveList[i]
      if(liveList[i].isSelect == 1){
        liveIds+= liveIds.length > 0 ? ',' : '';
        liveIds += liveList[i].Id + ',';
      }
    }   
    if (!that.data.title) {
      utils.showToast('请输入标题'); return;
    }
    if (that.data.detailPics.length == 0) {
      utils.showToast('请先上传图片'); return;
    }
    if (that.data.detailPics.length > 6) {
      utils.showToast('最多选择6张！'); return;
    }
    if (that.getInt(that.data.sort)>=10000) {
      utils.showToast('排序不超过5位数字！'); return;
    }
    if(that.data.yjprice !='' && isNaN(that.data.yjprice)){
      utils.showToast('请输入佣金价格'); return;
    }
    if(that.industryCode ==5 || that.industryCode ==6){
      if(that.getFloat(that.data.costPrice) >= that.getFloat(that.data.bprice)){
        utils.showToast('成本价不能超过销售价'); return;
      }
    }    
    let data = {
      Uid: app.globalData.userInfo.Uid,
      Pid: that.data.pid,
      ProductName: that.data.title,
      CostPrice: that.getFloat(that.data.costPrice),
      ShopPrice: that.getFloat(that.data.bprice), //价格
      Description: that.data.description, //详情描述
      Images: that.data.detailPics, //头图
      DisplayOrder: that.getInt(that.data.sort), //排序
      VideoSrc: that.data.videoSrc, //视频 
      ShadowPrice: that.data.cutPoicy, //优惠政策
      StoreCid: that.data.StoreCid, //分类
      DetailPics: that.data.productPic, //产品详情图
      Stock: that.getInt(that.data.count), //库存
      State: that.data.state, //状态 0代表上架，1代表下架
      CateId: that.getInt(that.data.cateid), //195其他分类(单品), 375 优惠券商品, 376 套餐商品,377 品牌加盟, 378 技术培训
      OptionIds: optionids, //规格id, 多个逗号隔开
      UseEndTime: that.data.date, //有效期
      BuyType: that.data.selType,
      LiveIds: liveIds
    };
    
    wx.showModal({
      title: '提示',
      content: '是否确认提交！',
      success: function(res) {
        if (res.confirm) {
          wx.showLoading({title: '提交中',mask: true})
          wx.request({
            url: app.globalData.host + '/api/store/AddOrUpdateUserProduct',
            method: "POST",
            data: data,
            success: function(res) {
              wx.hideLoading();
              if (res.data.Code == 0) {
                utils.showToast('提交成功！');
                if (that.data.backpage == "index") {
                  wx.navigateBack();
                } else {
                  wx.redirectTo({url: '/pages/h5page/index?url=' + encodeURI('myProductList.html')})
                }
              } else {          
                utils.showModal(res.data.Message);
              }
            }
          })
        } 
      }
    })
  },

  //获取商品分类列表
  getGoodsClassList: function(pid,cardUid) {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/Store/GetStoreClassList?storeId=' + app.globalData.storeId + '&uid=' + cardUid,
      success: function(res) {
        if (res.data.Code == 0) {
          if (res.data.Data) {
            var list = res.data.Data;
            var newList = [{
              Name: "请选择产品标签"
            }];
            for (let i = 0; i < list.length; i++) {
              if(list[i].StoreCid>0){
                newList.push(list[i]);
              }
            }
            that.setData({
              classList: newList,
            })
            that.getGoodDetails(pid);
          }
        }
      },
    })
  },
  changeCateid: function(e) {
    this.setData({
      cateid: e.currentTarget.dataset.cateid
    })
  },
  changeState: function() {
    let state = this.data.state;
    this.setData({
      state: state == 1 ? 0 : 1
    });
  },

  toaddsku: function() {
    this.setData({
      showDialogSku: true
    })
  },

  selTag: function(e) {
    let that = this;
    let tagid = e.currentTarget.dataset.tagid;
    let skulist = that.data.skulist;
    let skulistChoose = [];
    for (let i = 0; i < skulist.length; i++) {
      if (skulist[i].TagId == tagid) {
        skulist[i].select = skulist[i].select == 0 ? 1: 0;
        break;
      }
    }
    for (let i = 0; i < skulist.length; i++) {
      if (skulist[i].select == 1) {
        skulistChoose.push(skulist[i]);
      }
    }

    that.setData({
      skulist: skulist,
      skulistChoose: skulistChoose
    })
  },

  bindTitleInput: function(e) {
    this.setData({
      title: e.detail.value
    })
  },
  cancel: function() {
    wx.navigateBack({
      delta: 1
    })
  },
  bindCounts: function(e) {
    this.setData({
      count: e.detail.value
    })
  },
  bindPrice: function(e) {
    this.setData({
      bprice: e.detail.value
    })
  },
  bindCostPrice: function(e){
    this.setData({
      costPrice: e.detail.value
    })
  },
  bindYjPrice: function(e){
    this.setData({
      yjprice: e.detail.value
    })
  },
  bindSortInput: function(e) {
    this.setData({
      sort: e.detail.value
    })
  },

  // 优惠政策
  bindCutPoicy: function(e) {
    this.setData({
      cutPoicy: e.detail.value
    })
  },
  bindDateChange: function(e) {
    this.setData({
      date: e.detail.value
    })
  },
  bindDescriptionInput: function(e) {
    this.setData({
      description: e.detail.value
    })
  },
  bindVideoInput: function(e) {
    this.setData({
      videoSrc: e.detail.value
    })
  },
  closedialog: function() {
    this.setData({
      showDialogSku: !this.data.showDialogSku
    })
  },
  
  bindPickerChange(e) {
    let list = this.data.classList;
    this.setData({
      indexk: e.detail.value,
      StoreCid: list[e.detail.value].StoreCid
    })
  },
  //监听用户滑动页面事件
  onPageScroll: function(e) {
    let top = parseInt(e.scrollTop) + 70;
    this.setData({
      top: top
    })
  },

  //调用子组件的方法生成海报
  sharePoste: function () {
    this.selectComponent('#getPoster').getAvaterInfo();    
  },
  myEventListener: function (e) {
    this.setData({
      showVideo: true
    })
  },

  onShareAppMessage: function () {
    var that = this;
    var cardid = wx.getStorageSync("cardId");
    return {
      imageUrl: that.data.showDetailPics[0],
      title: that.data.title,
      path: '/pages/index/index?id=' + cardid + '&source=2' + '&pid=' + that.data.pid,
      success: function (res) {
        utils.showModal('转发成功');
      }
    }
  },

  getFloat:function(text){
    if (text === undefined || text == '' || isNaN(text)){
      return 0;
    }
    return parseFloat(parseFloat(text).toFixed(2));
  },
  getInt:function(text){
    if (text === undefined || text == '' || isNaN(text)) 
      return 0;
    return parseInt(text);
  },
})